<?php

namespace App\Admin\Controllers;

use App\Admin\Actions\Post\UpdateWithdrawOk;
use App\Admin\Actions\Post\UpdateWithdrawFail;
use App\Admin\Actions\Post\WithdrawVerfyOk;
use App\Admin\Exports\WithdrawExport;
use App\Admin\Extensions\WithdrawVerify;
use App\Http\Controllers\Controller;
use App\Model\CoinLog;
use App\Model\Guild\GuildHost;
use App\Model\Message;
use App\Model\ProfileVerifyLog;
use App\Model\SocialAccount;
use App\Model\User;
use App\Model\UserCoin;
use App\Model\UserProfilePersonal;
use App\Model\Withdraw;
use App\Util\InfoUtil;
use App\Util\YzhUtil;
use Encore\Admin\Grid;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Form;
use Encore\Admin\Controllers\ModelForm;
use Encore\Admin\Layout\Content;
use Exception;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use App\Admin\Actions\Post\UpdateWithdrawOkXmi;
class WithdrawController extends Controller
{
    use ModelForm;

    /**
     * Index interface.
     *
     * @return Content
     */
    public function index()
    {
        $this->isAdmin = Admin::user()->inRoles(['administrator']);
        return Admin::content(function (Content $content) {
            $content->header('提现审核');
            $yzhAccount = YzhUtil::queryAccounts();
            if (!isset($yzhAccount['data'])) $info = '';
            else {
                $actBalance = $yzhAccount['data']['dealer_infos'][0]['acct_balance'];
                $rebateBalance = $yzhAccount['data']['dealer_infos'][0]['rebate_fee_balance'];
                $info = "云账户余额：{$actBalance}；返点余额：{$rebateBalance}  <span style='margin-right: 2rem;'></span>  |";
            }
//            $yzhAccountXmi = YzhUtil::queryAccounts('yzh_xmi');
//            if(isset($yzhAccountXmi['data'])){
//                $actBalanceXmi = $yzhAccountXmi['data']['dealer_infos'][0]['acct_balance'];
//                $rebateBalanceXmi = $yzhAccountXmi['data']['dealer_infos'][0]['rebate_fee_balance'];
//                $info .= " <span style='margin-left: 2rem'>芯米云账户余额：{$actBalanceXmi}；返点余额：{$rebateBalanceXmi}</span>";
//            }

            $content->description($info);
            $adminId = Admin::user()->id;
            if (in_array($adminId, [7, 11])) $content->body('暂未开放');
            else $content->body($this->grid());
        });
    }

    public function edit($id)
    {
        $content = new Content();
        $content->header('编辑');
        $content->body($this->form()->edit($id));
        return $content;
    }

    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        // return Admin::grid(Withdraw::class, function (Grid $grid) {
        $guildHosts = GuildHost::getAllHostsStatusAll();//获取推广人员
        $wechatHostIds = ProfileVerifyLog::wechatHostIds();
        $grid = new Grid(new Withdraw());
        $where = [
            // ['status', Withdraw::STATUS_ING]
        ];
        if (request()->status == null) {
            request()->merge(['status' => Withdraw::STATUS_ING]);
        }
        $grid->model()->where($where)->orderBy('id', 'desc');
        $grid->tools(function (Grid\Tools $tools) {
            $tools->append(new UpdateWithdrawOk());
//            $tools->append(new UpdateWithdrawOkXmi());
            $tools->append(new UpdateWithdrawFail());
            $tools->batch(function (Grid\Tools\BatchActions $actions) {
                $actions->disableDelete();
            });
        });
        $grid->id('记录ID');
        $grid->userProfile()->user_profile_id('用户ID')->display(function ($data) {
            return "{$data}（内部ID：{$this->user_id}）";
        });
//        $grid->is_guild('是否代理女用户')->display(function ($data) use ($guildHosts) {
//            return isset($guildHosts[$this->user_id]) ? $guildHosts[$this->user_id] : '';
//        });
        $grid->userItem()->status('当前用户状态')->display(function ($data) {
            return User::STATUS[$data] ?? '未知';
        });
        $grid->userProfile()->nick_name('昵称');
        $grid->userProfile()->gender('性别')->display(function ($gender) {
            return $gender == 1 ? '男' : ($gender == 0 ? '女' : '-');
        });
        $grid->wechatVrf('微信认证')->display(function ($data) use ($wechatHostIds) {
            return in_array($this->user_id, $wechatHostIds) ? '已认证' : '';
        });
        $grid->personalProfile()->real_name('姓名');
        $grid->personalProfile()->id_card('身份证号');
        $grid->personalProfile()->wechat_openid('微信OpenID');
        $grid->personalProfile()->alipay_account('支付宝账号');
        $grid->personalProfile()->bank_card('银行卡号');
        $grid->personalProfile()->phone('手机号')->display(function ($data) {
            if (!$data) return '';
            return substr($data, 0, 3) . "****" . substr($data, -4);
        });
        $grid->withdraw_coin('提现金币')->totalRow(function ($data) {
            return "<span class='text-danger text-bold'>总金币：{$data}</span>";
        });
        $grid->withdraw_rmb('到账人民币金额')->totalRow(function ($data) {
            return "<span class='text-danger text-bold'>总额：<i class='fa fa-yen'></i>" . round($data, 1) . "</span>";
        });
        $grid->created_at('申请时间')->display(function ($time) {
            return !$time ? '-' : date('Y-m-d H:i:s', strtotime($time));
        });
        $grid->updated_at('记录更新时间')->display(function ($time) {
            return !$time ? '-' : date('Y-m-d H:i:s', strtotime($time));
        });
        $grid->yzh_order_id('代付三方单号');
        $grid->withdraw_way('结算渠道')->display(function ($data) {
            return Withdraw::getWithdrawWay($data);
        });
        $grid->account_type('到账方式')->display(function ($data) {
            return Withdraw::getAccountType($data);
        });
//        $grid->subject('提现主体')->display(function ($data) {
//            $account_type  =Withdraw::getAccountType($this->account_type);
//            return empty($account_type) || $account_type == '未知' ? '未知' : Withdraw::getSubject($data);
//        });
        $grid->out_trans_id('商户号提现交易号')->editable();
        $grid->status('处理结果')->display(function ($data) {
            $str = Withdraw::STATUS[$data];
            if ($data == Withdraw::STATUS_YZH_ERR && $this->yzh_detail) {
                $detail = json_decode($this->yzh_detail, true);
                $str = "提现异常：{$detail['detail']}（{$detail['status']}）";
            }
            return $str;
        });

        //禁用导出
        // $grid->disableExport();
        //禁用行选择
//        $grid->disableRowSelector();
        // $grid->disableActions();
        // $grid->disableCreateButton();

        $grid->exporter(new WithdrawExport($grid));
        $grid->filter(function ($filter) use($guildHosts){
            $filter->expand();
            // $filter->disableIdFilter();
            $filter->column(1 / 3, function ($filter) {
                $filter->equal('userProfile.user_profile_id', '用户ID');
                $filter->between('updated_at', '审核时间')->datetime();
                $filter->equal('withdraw_way', '结算渠道')->select(Withdraw::WITHDRAW_WAY);
                $filter->equal('userItem.status', '用户状态')->select(User::STATUS);
            });
            $filter->column(1 / 3, function ($filter) {
                $filter->equal('status', '审核状态')->select(Withdraw::STATUS);
                $filter->between('withdraw_rmb', '打款金额');
                $filter->startsWith('personalProfile.wechat_openid', '微信openID')->default('');
//                $filter->equal('subject', '支付主体')->select(Withdraw::SUBJECT);
            });
            $filter->column(1 / 3, function ($filter) {
                $filter->between('created_at', '提交时间')->datetime();
                $filter->equal('yzh_order_id', '云账户订单');
                $filter->equal('account_type', '收款方式')->select(Withdraw::ACCOUNT_TYPE);
                $filter->equal('sec_in_arrive', '秒到账订单')->select(Withdraw::SEC_IN_ARRIVE);
            });

            $filter->column(1 / 3, function ($filter) {
//                $filter->where(function ($query) {
//                    $userIds = GuildHost::where('guild_manage_id', $this->input)->pluck('host_user_id')->toArray();
//                    $query->whereIn('user_id', $userIds);
//                }, '所属代理')->select('/get_guilds_all');
            });
        });

        $isAdmin = $this->isAdmin;
        $adminUid = Admin::user()->id;
        $withdrawalBtUid = config('busi.withdrawal_bt_uid') ? config('busi.withdrawal_bt_uid') : [];

        $grid->actions(function (Grid\Displayers\Actions $actions) use ($isAdmin,$adminUid,$withdrawalBtUid) {
            $actions->disableDelete();
            $actions->disableEdit();
            $actions->disableView();
            if ($isAdmin || in_array($adminUid,$withdrawalBtUid)) {
                $actions->append(new WithdrawVerify(
                    $actions->getKey(),
                    $actions->row,
                    'withdraw/verify'
                ));
            }
        });

//        $grid->batchActions(function ($batch) {
//            $batch->add(new WithdrawVerfyOk());
//        });
        return $grid;
    }

    function verify()
    {
        $id = request('id');
        $status = request('status');
        $action = request('action');
        $ret = ['ret' => 0, 'message' => '操作成功！'];


        DB::beginTransaction();
        try {
            $record = Withdraw::find($id);

            if (!$record) return ['ret' => -1, 'message' => '记录不存在'];
            if ($record->status == $status) {
                return ['ret' => -1, 'message' => '该记录已经操作过，无法重复操作'];
            }

            if (
                $record->out_trans_id &&
                ($status == Withdraw::STATUS_FAIL || request('extra') == 'yzh')
            ) {
                return ['ret' => -1, 'message' => '已填写交易单号，无法进行该操作'];
            }

            //提现失败
            if ($status == Withdraw::STATUS_FAIL) {
                if ($record->out_trans_id) {
                    return ['ret' => -1, 'message' => '已填写商户号提现交易号，无法进行该操作～'];
                }
                //修改状态
                Withdraw::where('id', $id)->limit(1)->update(['status' => $status]);
                $userCoin = UserCoin::gainIncome($record->user_id, $record->withdraw_coin);
                CoinLog::addIncome($record->user_id, $record->withdraw_coin, CoinLog::FROM_WITHDRAW_BACK, $userCoin);
                //云账户异常
                if ($action == 'yzh_err_back') {
                    if (!$record->yzh_detail) $msg = "提现金币已退还，请重新校对信息后再申请提现～";
                    else {
                        $detail = json_decode($record->yzh_detail, true);
                        $msg = "你的{$detail['detail']}，提现金币已退还，请重新校对信息后再申请提现～";
                    }
                    Message::pushSystem($record->user_id, $msg, '提现通知');
                } else {
                    //不允许提现申请
                    Message::pushSystem($record->user_id, '你的提现申请暂不通过！如有疑问，请联系在线客服', '提现通知');
                }
            }
            //确认提现
            elseif ($status == Withdraw::STATUS_OK) {

                //判断用户状态
                $userInfo = User::find($record->user_id);
                if($userInfo->status != 0 ){
                    $str =  $userInfo->status == 1 ? '该用户已被冻结，无法正常提现' : '该用户已注销，无法正常提现';
                    return ['ret' => -1, 'message' => $str];
                }

                $payWay = request('extra');
                $withdrawWay = '';
                switch ($payWay) {
                    case 'yzh':
                        $ret = Withdraw::doYzhOrder($record->toArray());
                        $withdrawWay = isset($ret['bind_type']) && $ret['bind_type'] == UserProfilePersonal::BIND_TYPE_ALI ? '支付宝' : '银行卡';
                        Log::info(__CLASS__ . "WithdrawId:{$id}==Payway:{$payWay}==UserId:{$record->user_id}==" . json_encode($ret));
                        break;
                    case 'yzh_xmi':
                        $ret = Withdraw::doYzhOrder($record->toArray());
                        $withdrawWay = isset($ret['bind_type']) && $ret['bind_type'] == UserProfilePersonal::BIND_TYPE_ALI ? '支付宝' : '银行卡';
                        Log::info(__CLASS__ . "WithdrawId:{$id}==Payway:{$payWay}==UserId:{$record->user_id}==" . json_encode($ret));
                        break;
                    case 'wechat':
                    case 'alipay':
                        Log::info(__CLASS__ . "WithdrawId:{$id}==Payway:{$payWay}==UserId:{$record->user_id}");
                        break;
                    //杉德
                    case 'sand':
                        $withdrawWay = '银行卡';
                        $ret = Withdraw::doSandOrder($record->toArray());
                        Log::info(__CLASS__ . "WithdrawId:{$id}==Payway:{$payWay}==UserId:{$record->user_id}==" . json_encode($ret));
                        break;
                    case 'mst_alipay':
                    case 'mst_alipay_bank':
                        $withdrawWay = ($payWay == "mst_alipay") ? "支付宝" : '银行卡';
                        $ret = Withdraw::doMstOrder($record->toArray(), $payWay);
                        Log::info(__CLASS__ . "WithdrawId:{$id}==Payway:{$payWay}==UserId:{$record->user_id}==" . json_encode($ret));
                        break;
                }
                //提现审核已经通过
                if ($ret['ret'] == 0) {
                    $time = date('Y年m月d日', strtotime((string)$record->created_at));
                    $pushMsg = "你于{$time}申请的提现已通过审核，请注意查收你的{$withdrawWay}账号！";
                    Message::pushSystem($record->user_id, $pushMsg, '提现通知');
                    Withdraw::where('id', $id)->limit(1)->update([
                        'status' => $status,
                        'withdraw_way' => $payWay
                    ]);
                }
            }
            DB::commit();
            // else DB::rollBack();
        } catch (Exception $e) {
            DB::rollBack();
            Log::info(__CLASS__ . "==WithdrawId:{$id}==Exception:" . $e->getMessage());
            return ['ret' => -1, 'message' => '提现提交异常！'];
        }
        return $ret;
    }

    public function create()
    {
        return Admin::content(function (Content $content) {
            $content->header('批量修改提现成功状态');
            $content->description('');
            $content->body($this->form());
        });
    }

    protected function form($mode = '', $id = '')
    {
        // return Admin::form(Withdraw::class, function (Form $form) use ($mode, $id) {
        $form = new Form(new Withdraw());
        $form->textarea('withdraw_id', '提现记录ID')->rows(10)->default('');
        $form->select('withdraw_way', '结算渠道')->options(Withdraw::WITHDRAW_WAY);
        $form->select('accont_type', '收款方式')->options(Withdraw::ACCOUNT_TYPE);
        $form->saving(function (Form $form) {
            $withdrawIds = explode("\r\n", trim($form->withdraw_id));
            $count = count($withdrawIds);
            //修改提现状态
            $ret = Withdraw::whereIn('id', $withdrawIds)->limit($count)->update([
                'status' => Withdraw::STATUS_OK,
                'withdraw_way' => $form->withdraw_way,
                'account_type' => $form->accont_type,
            ]);
            $accountType = Withdraw::ACCOUNT_TYPE[$form->accont_type] ?? '收款账户';
            $pushMsg = "你申请的提现已通过审核，请注意查收你的{$accountType}！";
            $userIds = Withdraw::whereIn('id', $withdrawIds)->pluck('user_id')->toArray();
            $userIds = array_unique($userIds);
            // $count = count($userIds);
            Message::pushSystem($userIds, $pushMsg, '提现通知');
            Log::info(__CLASS__ . "==Ids:" . json_encode($withdrawIds) . "==Uids:" . json_encode($userIds) . "==Count:{$count}" . "==Msg:{$pushMsg}");
            return InfoUtil::adminSuc("成功修改{$count}条记录的提现状态～");
        });
        $form->tools(function (Form\Tools $tools) {
            $tools->disableList();
            $tools->disableDelete();
            $tools->disableView();
            $tools->disableView();
        });
        return $form;
    }
}
